<template>
  <div class="testadd">
    <div class="createTest"><span class="create">创建考试</span></div>
    <div class=""></div>
    <!-- 基本信息 -->
    <div class="basic">
      <div class="one">
        <span class="ones">1</span>
        <span style="padding-left: 17px">基本信息</span>
      </div>
      <div class="from">
        <el-form
          ref="formRef"
          :model="data"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="考试名称：" prop="title">
            <el-input v-model="params.title" type="text" autocomplete="off" />
          </el-form-item>
          <el-form-item label="考试说明：" prop="info">
            <el-input
              v-model="params.info"
              type="textarea"
              autocomplete="off"
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 内容设置 -->
    <div class="Setup">
      <div class="one">
        <span class="ones">2</span>
        <span style="padding-left: 17px">内容设置</span>
      </div>
      <div class="content">
        <el-form
          ref="formRef"
          :model="data"
          label-width="110px"
          class="demo-ruleForm"
        >
          <el-form-item label="考试内容：" prop="content">
            <div class="god">
              <div class="godTop">
                <h3>试题列表</h3>
                <div class="right">
                  <span>总分：{{ Total }}</span>
                  <span class="ad">已添加{{ params.questions.length }}题</span>
                  <el-button style="font-size: 13px" @click="dell"
                    >清空</el-button
                  >
                </div>
              </div>
              <div class="testContent" v-show="params.questions.length > 0">
                <div class="dan" v-if="dan == true">
                  <span style="margin-left: 10px">单选题{{ num11 }}道</span>
                  <p style="margin-left: 10px" class="mei">
                    每题<el-input v-model="num1" />分
                  </p>
                </div>
                <div class="dan" v-if="duo">
                  <span style="margin-left: 10px">多选题{{ num12 }}道</span>
                  <p style="margin-left: 10px" class="mei">
                    每题<el-input v-model="num2" />分
                  </p>
                </div>
                <div class="dan" v-if="pan">
                  <span style="margin-left: 10px">判断题{{ num15 }}道</span>
                  <p style="margin-left: 10px" class="mei">
                    每题<el-input v-model="num3" />分
                  </p>
                </div>
                <div class="dan" v-if="tian">
                  <span style="margin-left: 10px">填空题{{ num13 }}道</span>
                  <p style="margin-left: 10px" class="mei">
                    每题<el-input v-model="num4" />分
                  </p>
                </div>
                <div class="jian" v-if="wen">
                  <span style="margin-left: 10px">问答题{{ num14 }}道</span>
                  <p style="margin-left: 10px" class="mei">
                    每题<el-input v-model="num5" />分
                  </p>
                </div>
              </div>
              <!-- 试题添加开始 -->
              <div class="gotContentBox" v-show="params.questions.length > 0">
                <div
                  class="gotContent"
                  v-for="(item, index) in params.questions"
                  :key="item.id"
                >
                  <div class="gotTop">
                    <div class="gotLeft">
                      <span>{{ index + 1 + "." + item.type }}</span>
                      <span style="padding-left: 10px">分值</span>
                      <el-form-item>
                        <el-input v-model="item.scores" />
                      </el-form-item>
                    </div>
                    <div class="gotRight">
                      <span
                        ><el-icon @click="upd(item, index)"><EditPen /></el-icon
                      ></span>
                      <span style="padding: 0px 10px"
                        ><el-icon @click="del(index, item.type)"
                          ><Delete /></el-icon
                      ></span>
                    </div>
                  </div>
                  <div style="padding: 7px 0px" v-html="rep(item.title)"></div>
                  <div
                    v-show="item.type === '单选题'"
                    :class="
                      item.answer === items.answerno ? 'options' : 'optio'
                    "
                    v-for="items in item.answers"
                    :key="items.id"
                  >
                    <el-radio :label="items.answerno + '：'"></el-radio>
                    <span>{{ items.content }}</span>
                  </div>
                  <div
                    v-show="item.type === '多选题'"
                    :class="
                      item.answer.indexOf(items.answerno) != -1
                        ? 'options'
                        : 'optio'
                    "
                    v-for="items in item.answers"
                    :key="items.id"
                  >
                    <el-checkbox :label="items.answerno + '：'"></el-checkbox>
                    <span>{{ items.content }}</span>
                  </div>
                  <div
                    v-if="item.type === '填空题' || item.type === '判断题'"
                    class="judge"
                  >
                    <span>正确答案</span>
                    <span style="margin-left: 20px">{{ item.answer }}</span>
                  </div>
                  <div
                    v-if="item.type === '填空题' || item.type === '问答题'"
                    class="jud"
                  >
                    <span>答案解析：</span>
                    <span>{{ item.explains }}</span>
                  </div>
                </div>
              </div>

              <!-- 试题添加结束 -->
              <div class="button">
                <el-button style="font-size: 13px" @click="addTitle"
                  >添加题目</el-button
                >
                <el-button style="font-size: 13px" @click="batchImport">批量导入</el-button>
                <el-button style="font-size: 13px" @click="baseD"
                  >从题库中导入</el-button
                >
                <el-button style="font-size: 13px" @click="isPaper"
                  >选择已有试卷</el-button
                >
              </div>
            </div>
          </el-form-item>
          <el-form-item label="试题存入题库：" prop="content">
            <el-select v-model="region" placeholder="请选择题库">
              <el-option
                v-for="item in regions"
                :label="item.title"
                :value="item.id"
                :key="item.id"
              />
            </el-select>
            <el-button
              style="font-size: 13px; margin-left: 13px"
              @click="addBase"
              >+ 创建试题库</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 引入题库列表组件 -->
    <List :state="state" :name="name"></List>
    <!-- 引入添加题库对话框 -->
    <AddBase :Addis="Addis" @addBases="addBases"></AddBase>
    <!-- 考试设置 -->
    <div class="Testset">
      <div class="one">
        <span class="ones">3</span>
        <span style="padding-left: 17px">考试设置</span>
      </div>
      <div class="set">
        <el-form class="demo-form-inline" label-width="120px">
          <el-form-item label="通过分数：">
            <el-input
              v-model="params.pastscores"
              type="number"
              style="width: 90px"
            />
          </el-form-item>
          <el-form-item label="考试时长：">
            <el-radio-group v-model="params.isshow" class="ml-4">
              <el-radio :label="1" size="large">不限时时长</el-radio>
              <el-radio :label="2" size="large">限时时长</el-radio>
              <el-input
                type="number"
                style="width: 90px"
                v-model="params.limittime"
                v-if="params.isshow == 2"
              />
            </el-radio-group>
            <span style="margin-left: 10px" v-if="params.isshow == 2"
              >分钟</span
            >
          </el-form-item>
          <div class="time">
            <el-form-item label="开放时间：">
              <el-date-picker
                v-model="arrTime"
                type="datetimerange"
                :shortcuts="shortcuts"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                @change="changeTime"
                format="YYYY-MM-DD HH:mm"
              />
            </el-form-item>
            <span class="bu">不填表示永久</span>
          </div>
          <el-form-item label="答案解析：">
            <el-radio-group v-model="params.answershow" class="ml-4">
              <el-radio :label="1" size="large">交卷后显示</el-radio>
              <el-radio :label="2" size="large">不允许查看</el-radio>
              <el-radio :label="3" size="large">仅可查看对错</el-radio>
              <el-radio :label="4" size="large">仅查看错题</el-radio>
              <el-radio :label="5" size="large">考试结束后查看</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="防作弊：">
            <el-checkbox
              v-model="params.qorder"
              label="试题顺序打乱"
              size="large"
              :true-label="1" :false-label="0"
              @change="chanSub"
            />
            <el-checkbox
              v-model="params.aorder"
              label="选项顺序打乱(单选题,多选题,判断题)"
              size="large"
              :true-label="1" :false-label="0"
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 教师范围 -->
    <div class="Teachers">
      <div class="one">
        <span class="ones">4</span>
        <span style="padding-left: 17px">教师范围</span>
      </div>
      <div class="viTeacher">
        <el-form class="demo-form-inline">
          <el-form-item label="可见老师：">
            <el-badge :value="params.limits.length" class="item" type="primary">
              <el-button style="font-size: 13px; width: 72px" @click="teacher"
                >+ 选择</el-button
              >
            </el-badge>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 引入学生对话框 -->
    <Student
      :is="is"
      @iss="iss"
      :stu="stus"
      @marks="marks"
      @students="students"
      @limitss="limitss"
    ></Student>
    <!-- 引入添加题目对话框 -->
    <Drawer :isTitle="isTitle" v-if="isTitle" :index="index" @isF="isF" :obj="obj"></Drawer>
    <!-- 考试学生 -->
    <div class="Teachers">
      <div class="one">
        <span class="ones">5</span>
        <span style="padding-left: 17px">考试学生</span>
      </div>
      <div class="viTeacher">
        <el-form class="demo-form-inline">
          <el-form-item label="考生范围：">
            <el-badge
              :value="params.students.length"
              class="item"
              type="primary"
            >
              <el-button style="font-size: 13px; width: 72px" @click="student"
                >+ 选择</el-button
              >
            </el-badge>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <ItemList></ItemList>
    <!-- 协同设置 -->
    <div class="Teachers">
      <div class="one">
        <span class="ones">6</span>
        <span style="padding-left: 17px">协同设置</span>
      </div>
      <div class="viTeacher">
        <el-form class="demo-form-inline">
          <el-form-item label="阅卷老师：">
            <el-badge
              :value="params.markteachers.length"
              class="item"
              type="primary"
            >
              <el-button style="font-size: 13px; width: 72px" @click="vteacher"
                >+ 选择</el-button
              >
            </el-badge>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="but">
      <el-button type="primary" @click="release">发布</el-button>
      <el-button style="padding: 0px 10px" @click="noRelease">保存(不发布)</el-button>
      <el-button @click="qu">取消</el-button>
    </div>
  </div>
  <!-- 批量导入 -->
  <Import @imports="imports" :isImport="isImport" @isImports="isImports"></Import>
</template>

<script lang='ts' setup>
import { provide, reactive, toRefs, watch, watchEffect } from "vue";
// 引入字体图标
import { Delete, EditPen } from "@element-plus/icons-vue";
// 引入封装的组件
import Student from "../../components/test/student.vue";
import ItemList from "../../components/test/ItemList.vue";
import List from "../../components/test/List.vue";
import AddBase from "../../components/test/AddBase.vue";
import Drawer from "../../components/test/Drawer.vue";
// 引入题库接口 题库添加 根据id获取单条数据
import { Database, Add, getTest } from "../../apis/test/test";
import { ElMessage } from "element-plus";
import { useRouter, useRoute } from "vue-router";
// 引入moent
import moment from "moment";
// 引入批量导入
import Import from '../../components/test/Import.vue'

const data: any = reactive({
  params: {
    id: 0,
    title: "",
    info: "",
    admin: "ldq",
    begintime: "",
    endtime: "",
    // 限制时长
    limittime: "",
    scores: 100,
    state:null,
    // 通过分数
    pastscores: 60,
    qorder: 0,
    aorder: 0,
    answershow: 1,
    isshow:1,
    databaseid: 20,
    // 可见老师
    limits: [],
    // 阅卷老师
    markteachers: [],
    // 考生范围
    students: [],
    // 试题添加数据
    questions: [],
  },
  qor:[],
  aor:[],
  // 实体存入题库
  region: [],
  regions: [],
  // 分值
  score: "",
  // 防作弊
  checked1: "",
  checked2: true,
  // 弹可见老师
  is: false,
  // 带参数
  stus: "",
  // 弹出题库列表
  state: false,
  // 弹出框标题
  name: "",
  // 弹出添加对话框
  Addis: false,
  // 弹出添加试卷
  isTitle: false,
  Total: 0,
  // 根据id获取单条试卷
  DataList: [],
  // 题库ID
  dataID: 0,
  num1: "",
  num2: "",
  num3: "",
  num4: "",
  num5: "",
  dan: false,
  duo: false,
  pan: false,
  tian: false,
  wen: false,
  arrType: <any>[],
  isShow: false,
  isShow1: false,
  nums: 0,
  // 考试ID
  test: 0,
  num11: 0,
  num12: 0,
  num13: 0,
  num14: 0,
  num15: 0,
  arrTime: [],
  obj: {},
  Tips: "",
  index: -1,
  isImport:false
});
const {
  isImport,
  obj,
  arrTime,
  num11,
  num12,
  num13,
  num14,
  num15,
  dan,
  duo,
  pan,
  tian,
  wen,
  num1,
  num2,
  num3,
  num4,
  num5,
  Total,
  params,
  region,
  is,
  stus,
  regions,
  state,
  name,
  Addis,
  isTitle,
  index,
}: any = toRefs(data);
// 富文本替换
const rep = (str: string) => {
  return str.replace(/\[\]/g, `_______,`);
};
// 批量导入
const isImports=(e:any)=>{
  isImport.value=e
}
const batchImport=()=>{
  isImport.value = true
}
// 日期
const shortcuts = [
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "最近一个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "最近三个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];
// 接受子传来的值
const iss = (e: any) => {
  is.value = e;
};

// 可见老师子传父
const limitss = (e: any) => {
  e.map((item: any) => params.value.limits.push({ id: item }));
};
// 可见老师
const teacher = () => {
  is.value = true;
  stus.value = "可见";
};
// 考生范围子传父
const students = (e: any) => {
  e.map((item: any) => params.value.students.push({ studentid: item }));
};

// 考试学生
const student = () => {
  is.value = true;
  stus.value = "学生";
};
// 阅卷老师子传父
const marks = (e: any) => {
  e.map((item: any) => params.value.markteachers.push({ id: item }));
};
// 阅卷老师
const vteacher = () => {
  is.value = true;
  stus.value = "阅卷老师";
};

provide("data", data);
// 题库列表
const base = async () => {
  const res: any = await Database({});
  if (res.errCode) {
    data.regions = res.data.list;
  } else {
    ElMessage.error(res.errMsg);
  }
};
base();
const isF = (e: any) => {
  isTitle.value = e;
};
// 弹出题库对话框
const baseD = () => {
  data.isShow = true;
  name.value = "题库列表";
};
// 弹出试卷对话框
const isPaper = () => {
  data.isShow = true;
  name.value = "试卷列表";
};
// 添加题库子传父
const addBases = (e: any) => {
  Addis.value = e;
};
// 添加题库
const addBase = () => {
  Addis.value = true;
};
// 添加题目
const addTitle = () => {
  isTitle.value = true;
  data.index = -1;
  data.obj ={};
};
// watch监听
watchEffect(() => {
  let num6 = 0;
  let num7 = 0;
  let num8 = 0;
  let num9 = 0;
  let num10 = 0;
  params.value.questions.forEach((item: any) => {
    if (item.type === "单选题") {
      data.dan = true;
      num6 += 1;
      // console.log(dan.value)
    } else if (item.type === "多选题") {
      duo.value = true;
      num7 += 1;
      // nums.value+1
    } else if (item.type === "填空题") {
      tian.value = true;
      num8 += 1;
      // nums.value+=1
    } else if (item.type === "问答题") {
      wen.value = true;
      num9 += 1;
      // nums.value+=1
    } else if (item.type === "判断题") {
      pan.value = true;
      num10 += 1;
    }
  });
  num11.value = num6;
  num12.value = num7;
  num13.value = num8;
  num14.value = num9;
  num15.value = num10;
});
// 日期内容改变
const changeTime = (e: any) => {
  const begintime = moment(e[0]).format("YYYY-MM-DD HH:mm:ss.0");
  const endtime = moment(e[1]).format("YYYY-MM-DD HH:mm:ss.0");
  data.arrTime.push(begintime);
  data.arrTime.push(endtime);
  params.value.begintime = begintime;
  params.value.endtime = endtime;
};
// 删除
const del = (index: number, type: String) => {
  if (type === "单选题") {
    if (num11.value > 1) {
      num11.value -= 1;
    }
    data.dan = false;
    params.value.questions.splice(index, 1);
  }
  if (type === "多选题") {
    data.duo = false;
    params.value.questions.splice(index, 1);
  }
  if (type === "判断题") {
    data.pan = false;
    params.value.questions.splice(index, 1);
  }
  if (type === "填空题") {
    data.tian = false;
    params.value.questions.splice(index, 1);
  }
  if (type === "问答题") {
    data.wen = false;
    params.value.questions.splice(index, 1);
  }
};
// 清空
const dell = () => {
  params.value.questions = [];
  dan.value = false,
  duo.value = false,
  pan.value = false,
  tian.value = false,
  wen.value = false
};

// 小修改
const upd = (row: any, index: number) => {
  row.title = row.title.startsWith('<p>') ? row.title : `<p>${row.title}</p>`
  console.log(row.title)
  data.obj = JSON.parse(JSON.stringify(row))
  isTitle.value = true;
  data.index = index;
};

// 监听
watchEffect(() => {
  var num = 0;
  params.value.questions.map((item: any, index: number) => {
    num = Number(item.scores) + Number(num);
  });
  Total.value = num;
});
watch([num1], () => {
  params.value.questions.map((item: any) => {
    if (item.type === "单选题") {
      item.scores = num1.value;
    }
  });
});
watch([num2], () => {
  params.value.questions.map((item: any) => {
    if (item.type === "多选题") {
      item.scores = num2.value;
    }
  });
});
watch([num3], () => {
  params.value.questions.map((item: any) => {
    if (item.type === "判断题") {
      item.scores = num3.value;
    }
  });
});
watch([num4], () => {
  params.value.questions.map((item: any) => {
    if (item.type === "填空题") {
      item.scores = num4.value;
    }
  });
});
watch([num5], () => {
  params.value.questions.map((item: any) => {
    if (item.type === "问答题") {
      item.scores = num5.value;
    }
  });
});
// router传参
const router = useRouter();
// route接收参数
const route: any = useRoute();
let id = route.params["id"];

// 数据回显
const Echo = async () => {
  console.log({ id: Number(id) });
  const res: any = await getTest(Number(id));
  console.log(res)
  if (res.errCode === 10000) {
    data.params = res.data;
    data.arrTime.push(res.data.begintime);
    data.arrTime.push(res.data.endtime);
  } else {
    ElMessage.error(res.errMsg);
  }
};
if (Number(id) != 1) {
  Echo();
}

// 添加方法
const TesdAdd=async ()=>{
  params.value.qorder == true ? (params.value.qorder = 1) : params.value.qorder;
  params.value.aorder == true ? (params.value.aorder = 1) : params.value.aorder;
  params.value.begintime===""?params.value.begintime=null:params.value.begintime
  params.value.endtime===""?params.value.endtime=null:params.value.endtime
  
  if (!params.value.title) {
    ElMessage.error("请填写考试名称");
    return;
  } else if (!params.value.info) {
    ElMessage.error("请填写考试说明");
    return;
  } else if (params.value.questions.length === 0) {
    ElMessage.error("请添加题目");
    return;
  } else if (params.value.limits.length === 0) {
    ElMessage.error("请选择可见老师");
    return;
  } else if (params.value.students.length === 0) {
    ElMessage.error("请选择考生可见范围");
    return;
  } else if (params.value.markteachers.length === 0) {
    ElMessage.error("请选择阅卷老师");
    return;
  }

  if (Number(id) === 1) {
    Total.value = params.scores;
    // 添加
    const res: any = await Add(params.value);
    if (res.errCode === 10000) {
      ElMessage.success("添加成功！");
      router.push("/test");
    } else {
      ElMessage.error(res.errMsg);
    }

  } else {
    Total.value = params.scores;
    params.value.id = Number(id);
    const res: any = await Add(params.value);
    if (res.errCode === 10000) {
      ElMessage.success("修改成功!");
      router.push("/test");
    } else {
      ElMessage.error(res.errMsg);
    }
  }
}

// 点击发布
const release = async () => {
   params.value.state=1
   TesdAdd()
};

// 批量导入
const imports = (e:any)=>{
  params.value.questions = e
}

// 保存不发布
const noRelease=()=>{
  params.value.state=2
  TesdAdd()
}

// 取消关闭弹框
const qu = () => {
  router.push("/test");
};


// // 试题顺序打乱
// const chanSub=(e:any)=>{
//   if(e==1){
//     const shuffle = (arr:any)=>{
//       for(let i = 0; i < arr.length;i++){
//           var randomIndex = Math.floor(Math.random() * (i+1));
//           var itemAtIndex = arr[randomIndex]
//           arr[randomIndex] = arr[i];
//           arr[i] = itemAtIndex
//       }
//       return arr
//     }
//     params.value.questions = shuffle(params.value.questions)
    
//   }
// }
</script>
<style scoped>
@import url("../../static/css/test/testadd.css");
</style>